package ani.trainning.cacobatph.das;

import java.io.IOException;

import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.transport.ServiceConnection;
import org.ksoap2.transport.ServiceConnectionSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import ani.trainning.cacobatph.ConstantUtil;
import ani.trainning.cacobatph.R;
import ani.trainning.cacobatph.utilities;

public class Thr9_ValidationDAS {

	private final Handler mHandler;
	private final Context context;
	public final static int VALIDATION_DAS_OK=300;
	public final static int VALIDATION_DAS_FAILURE=-300;

	String user;
	String pass;
	_Entete entete;

	// constructor
	public Thr9_ValidationDAS(Handler handler,
			Context context, String _user, String _pass, _Entete entete) {
		mHandler = handler;
		this.context = context;
		this.user = _user;
		this.pass = _pass;
		this.entete = entete;
	}

	public Thread createThread() {
		return new Thread() {
			@Override
			public void run() {
				// creation du message.
				try {

					String response = validate(context, user, pass);

					// Recuperation de la reponse et l'envoi au handler.
					Message msg = new Message();
					msg.what = VALIDATION_DAS_OK;
					msg.obj = response;
					mHandler.sendMessage(msg);

				} catch (Exception e) {
					Message msg = new Message();
					msg.obj = e;
					if(e instanceof IOException)
						msg.what = ConstantUtil.EXCEPTION_IO2;
					else
						msg.what =VALIDATION_DAS_FAILURE	;
					Log.e("thread exeption : ", "" + e.getMessage());
					mHandler.sendMessage(msg);

				}

			}
		};
	}

	private String validate(final Context context, String userName,
			String passWord) throws Exception {

		SoapObject request = new SoapObject(context.getResources().getString(
				R.string.NAMESPACE), context.getResources().getString(
						R.string.VALIDATION_ERREURS_SANS_INCIDENCE_METHOD));

		PropertyInfo param = new PropertyInfo();
		param.setName("entete");
		param.setType(String.class);
		param.setValue(buildEntete());
		request.addProperty(param);

		param = new PropertyInfo();
		param.setName("isConfirmed");
		param.setType(Boolean.class);
		param.setValue(true);
		request.addProperty(param);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(request);

		envelope.headerOut = new Element[1];
		envelope.headerOut[0] = utilities.buildAuthHeader(context, userName, passWord);

		HttpTransportSE androidHttpTransport = new
		HttpTransportSE(context.getResources().getString(R.string.URL))
		{
			@Override
			protected ServiceConnection getServiceConnection()
			throws IOException {
				return new
				ServiceConnectionSE(context.getResources().getString(R.string.URL),
						ConstantUtil.TIMEOUT);
			}
		};
		androidHttpTransport.call(context.getResources().getString(R.string.NAMESPACE)
				+
				context.getResources().getString(R.string.VALIDATION_ERREURS_SANS_INCIDENCE_METHOD),
				envelope, null);

		String result = String.valueOf(envelope.getResponse());
		Log.i("chargement", "result : " + result);
		return result;

	}

	public Element buildBody(Context context) {
		Element h = new Element().createElement(context.getResources().getString(R.string.NAMESPACE), "ws06_das");
		Log.i("chargement", "h " + h.toString());

		//		Element _entete = new Element().createElement(context.getResources().getString(R.string.NAMESPACE), context.getResources()
		//				.getString(R.string.ENTETE));
		Element _entete = new Element();
		_entete.setName("entete");
		Log.i("chargement", "entete " + _entete.toString());

		Element nCotisant = new
		Element().createElement(context.getResources().getString(R.string.NAMESPACE), context.getResources().getString(R.string.N_COTISANT));
		nCotisant.addChild(Node.TEXT, entete.getnCotisant());
		_entete.addChild(Node.ELEMENT, nCotisant);
		Log.i("chargement", "ncotisant " + nCotisant.toString());

		Element annee = new
		Element().createElement(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.ANNEE_PARAM));
		annee.addChild(Node.TEXT, entete.getAnnee());
		_entete.addChild(Node.ELEMENT, annee);
		Log.i("chargement", "anne " + annee.toString());

		Element type = new
		Element().createElement(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.TYPE_PARAM));
		type.addChild(Node.TEXT, entete.getType());
		_entete.addChild(Node.ELEMENT, type);
		Log.i("chargement", "type " + type.toString());

		Element sommeSalairesAnn = new
		Element().createElement(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.SOMME_SALAIRES_ANNUEL));
		sommeSalairesAnn.addChild(Node.TEXT, Double.toString(entete.getSommeSalaireAnn()));
		_entete.addChild(Node.ELEMENT, sommeSalairesAnn);
		Log.i("chargement", "sommeSalairesAnn " + sommeSalairesAnn.toString());

		Element sommeSalariesDec = new
		Element().createElement(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.SOMME_SALAIRES_DEC));
		sommeSalariesDec.addChild(Node.TEXT, Integer.toString(entete.getSommeSalairesDec()));
		_entete.addChild(Node.ELEMENT, sommeSalariesDec);
		Log.i("chargement", "sommeSalariesDec " + sommeSalariesDec.toString());

		Element IdAgence = new
		Element().createElement(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.ID_AGENCE));
		IdAgence.addChild(Node.TEXT, entete.getIdAgence());
		_entete.addChild(Node.ELEMENT, IdAgence);
		Log.i("chargement", "IdAgence " + IdAgence.toString());

		Element numDas = new
		Element().createElement(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.NUM_DAS));
		numDas.addChild(Node.TEXT, Integer.toString(entete.getNumDas()));
		_entete.addChild(Node.ELEMENT, numDas);
		Log.i("chargement", "numDas " + numDas.toString());

		Element typePayDas = new
		Element().createElement(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.TYPE_PAY_DAS));
		typePayDas.addChild(Node.TEXT, entete.getTypePayDas());
		_entete.addChild(Node.ELEMENT, typePayDas);
		Log.i("chargement", "typePayDas " + typePayDas.toString());

		Element dateRecep = new
		Element().createElement(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.DATE_RECEP));
		dateRecep.addChild(Node.TEXT, entete.getDateRecep());
		_entete.addChild(Node.ELEMENT, dateRecep);
		Log.i("chargement", "dateRecep " + dateRecep.toString());

		Element isConfirmed = new Element().createElement(context
				.getResources().getString(R.string.NAMESPACE), context
				.getResources().getString(R.string.ISCONFIRMED));
		isConfirmed.addChild(Node.TEXT, "true");
		Log.i("chargement", "isConfirmed " + isConfirmed.toString());

		h.addChild(Node.ELEMENT, _entete);
		h.addChild(Node.ELEMENT, isConfirmed);
		return h;
	}

	public String buildEntete() throws Exception{
		JSONObject _entete=new JSONObject();
		_entete.put("n_cotisant", entete.getnCotisant());
		_entete.put("annee", entete.getAnnee());
		_entete.put("type", entete.getType());
		_entete.put("sommeSalairesAnn", entete.getSommeSalaireAnn());
		_entete.put("sommeSalariesDec", entete.getSommeSalairesDec());
		_entete.put("IdAgence", entete.getIdAgence());
		_entete.put("numDas", entete.getNumDas());
		_entete.put("typePayDas", entete.getTypePayDas());
		_entete.put("dateRecep", entete.getDateRecep());

		return _entete.toString();
	}
}
